import { loginApi } from '@/api/modules/user'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'

// 函数式action需要转换为对象action
const fetchUser = createAsyncThunk(
    'users/fetchUser',
    async (data) => {
        let res = await loginApi(data)

        // 返回值 返回给addCase
        return {
            token: res.token,
            username: res.user.name
        }
    }
)
export { fetchUser }

const initialState = JSON.parse(localStorage.getItem("user")) || {
    token: "",
    username: '',
}

// Then, handle actions in your reducers:
export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        // standard reducer logic, with auto-generated action types per reducer
    },
    extraReducers: (builder) => {
        // Add reducers for additional action types here, and handle loading state as needed
        builder.addCase(fetchUser.fulfilled, (state, action) => {
            state.token = action.payload.token
            state.username = action.payload.username
            localStorage.setItem("user", JSON.stringify(action.payload))
        })
    },
})
